package com.emex.app.stuff.shop;

import com.emex.app.stuff.security.SecurityManager;
import com.emex.app.shared.data.Position;
import com.emex.app.stuff.constant.ReportName;
import com.emex.app.stuff.gui.ConfirmPositionDialog;
import com.emex.app.stuff.gui.PositionDialog;
import com.emex.app.stuff.gui.PositionsToBuyDialog;
import com.emex.app.stuff.gui.model.PositionTableModel;
import com.emex.app.stuff.provider.ShopDataProvider;
import com.emex.app.stuff.utils.ExportUtils;
import com.emex.app.stuff.utils.MathUtils;
import com.emex.app.stuff.utils.ReportGenerator;
import com.emex.app.stuff.utils.StringUtilities;
import com.emex.app.stuff.utils.UIUtils;
import java.awt.image.BufferedImage;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.RowFilter;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.sf.jasperreports.engine.JasperPrint;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//com.emex.app.stuff.shop//Shop//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "ShopTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_NEVER
)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.emex.app.stuff.shop.ShopTopComponent")
@ActionReference(path = "Menu/Магазин" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_ShopAction",
        preferredID = "ShopTopComponent"
)
@Messages({
    "CTL_ShopAction=Магазин",
    "CTL_ShopTopComponent=Магазин",
    "HINT_ShopTopComponent=Магазин"
})
public final class ShopTopComponent extends TopComponent {

    private PositionTableModel positionTableModel;
    private PositionTableModel shopTableModel;
    private Position currentlyFoundPosition;
    private Set<Position> orderPositions = new HashSet<>();

    private Set<Position> positionsToPrint = new HashSet<>();

    public ShopTopComponent() {
        initComponents();
        setName(Bundle.CTL_ShopTopComponent());
        setToolTipText(Bundle.HINT_ShopTopComponent());
        analogsTable.setColumnControlVisible(true);
        analogsTable.setHorizontalScrollEnabled(true);
        analogsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int row = analogsTable.getSelectedRow();
                if ((row >= 0) && (row < analogsTable.getRowCount())) {
                    addAnalogToOrderButton.setEnabled(true);
                } else {
                    addAnalogToOrderButton.setEnabled(false);
                }
            }
        });
        if (!SecurityManager.getDefault().getCurrentPerson().getIsAdmin()) {
            deletePositionButton.setVisible(false);
        }
        customInit();
    }

    private void customInit() {
        shopTableModel = new PositionTableModel();
        shopTable.setModel(shopTableModel);
        calculateQuontity();
        shopTable.setColumnControlVisible(true);
        shopTable.setHorizontalScrollEnabled(true);
        shopTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int row = shopTable.getSelectedRow();
                if ((row >= 0) && (row < shopTable.getRowCount())) {
                    editPositionButton.setEnabled(true);
                    deletePositionButton.setEnabled(true);
                } else {
                    editPositionButton.setEnabled(false);
                    deletePositionButton.setEnabled(false);
                }
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        shopPanel = new javax.swing.JTabbedPane();
        searchPanel = new javax.swing.JPanel();
        findPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        searchField = new org.jdesktop.swingx.JXSearchField();
        analogsPanel = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        analogsTable = new org.jdesktop.swingx.JXTable();
        сurrentOrderPanel = new javax.swing.JPanel();
        currentOrderLink = new org.jdesktop.swingx.JXHyperlink();
        clearOrderButton = new javax.swing.JButton();
        resultScrollPanel = new javax.swing.JScrollPane();
        resultPanel = new javax.swing.JPanel();
        codeLabel = new javax.swing.JLabel();
        nameLabel = new javax.swing.JLabel();
        issuerLabel = new javax.swing.JLabel();
        priceLabel = new javax.swing.JLabel();
        purPriceLabel = new javax.swing.JLabel();
        amountLabel = new javax.swing.JLabel();
        minAmountLabel = new javax.swing.JLabel();
        placeLabel = new javax.swing.JLabel();
        codeTf = new javax.swing.JTextField();
        nameTf = new javax.swing.JTextField();
        issuerTf = new javax.swing.JTextField();
        priceTf = new javax.swing.JTextField();
        purPriceTf = new javax.swing.JTextField();
        amountTf = new javax.swing.JTextField();
        minAmountTf = new javax.swing.JTextField();
        placeTf = new javax.swing.JTextField();
        addAnalogToOrderButton = new javax.swing.JButton();
        stockPanel = new javax.swing.JPanel();
        searchControls = new javax.swing.JPanel();
        addPositionButton = new javax.swing.JButton();
        editPositionButton = new javax.swing.JButton();
        deletePositionButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        positionsToBuy = new javax.swing.JButton();
        localSearchField = new org.jdesktop.swingx.JXSearchField();
        searchLabel = new javax.swing.JLabel();
        printPriceLabelsLink = new org.jdesktop.swingx.JXHyperlink();
        clearPrintQueueButton = new javax.swing.JButton();
        addPositionToPrintPriceLabelButton = new javax.swing.JButton();
        exportToExcellButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        shopTable = new org.jdesktop.swingx.JXTable();
        jLabel2 = new javax.swing.JLabel();
        summaBuyTextField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        summaSellTextField = new javax.swing.JTextField();

        findPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.findPanel.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.jLabel1.text")); // NOI18N

        searchField.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.searchField.text")); // NOI18N
        searchField.setToolTipText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.searchField.toolTipText")); // NOI18N
        searchField.setSearchMode(org.jdesktop.swingx.JXSearchField.SearchMode.REGULAR);
        searchField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchFieldActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout findPanelLayout = new javax.swing.GroupLayout(findPanel);
        findPanel.setLayout(findPanelLayout);
        findPanelLayout.setHorizontalGroup(
            findPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(findPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(findPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(findPanelLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(158, 158, 158))
                    .addGroup(findPanelLayout.createSequentialGroup()
                        .addComponent(searchField, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        findPanelLayout.setVerticalGroup(
            findPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(findPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        analogsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.analogsPanel.border.title"))); // NOI18N

        jScrollPane2.setViewportView(analogsTable);

        javax.swing.GroupLayout analogsPanelLayout = new javax.swing.GroupLayout(analogsPanel);
        analogsPanel.setLayout(analogsPanelLayout);
        analogsPanelLayout.setHorizontalGroup(
            analogsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, analogsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2)
                .addContainerGap())
        );
        analogsPanelLayout.setVerticalGroup(
            analogsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, analogsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );

        сurrentOrderPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.сurrentOrderPanel.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(currentOrderLink, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.currentOrderLink.text")); // NOI18N
        currentOrderLink.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                currentOrderLinkActionPerformed(evt);
            }
        });

        clearOrderButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/delete.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(clearOrderButton, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.clearOrderButton.text")); // NOI18N
        clearOrderButton.setEnabled(false);
        clearOrderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearOrderButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout сurrentOrderPanelLayout = new javax.swing.GroupLayout(сurrentOrderPanel);
        сurrentOrderPanel.setLayout(сurrentOrderPanelLayout);
        сurrentOrderPanelLayout.setHorizontalGroup(
            сurrentOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(сurrentOrderPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(currentOrderLink, javax.swing.GroupLayout.DEFAULT_SIZE, 690, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(clearOrderButton)
                .addContainerGap())
        );
        сurrentOrderPanelLayout.setVerticalGroup(
            сurrentOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, сurrentOrderPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(сurrentOrderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(currentOrderLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(clearOrderButton))
                .addContainerGap())
        );

        resultScrollPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.resultScrollPanel.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(codeLabel, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.codeLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(nameLabel, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.nameLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(issuerLabel, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.issuerLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(priceLabel, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.priceLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(purPriceLabel, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.purPriceLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(amountLabel, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.amountLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(minAmountLabel, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.minAmountLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(placeLabel, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.placeLabel.text")); // NOI18N

        codeTf.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.codeTf.text")); // NOI18N
        codeTf.setEnabled(false);

        nameTf.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.nameTf.text")); // NOI18N
        nameTf.setEnabled(false);

        issuerTf.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.issuerTf.text")); // NOI18N
        issuerTf.setEnabled(false);

        priceTf.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.priceTf.text")); // NOI18N
        priceTf.setEnabled(false);

        purPriceTf.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.purPriceTf.text")); // NOI18N
        purPriceTf.setEnabled(false);

        amountTf.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.amountTf.text")); // NOI18N
        amountTf.setEnabled(false);

        minAmountTf.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.minAmountTf.text")); // NOI18N
        minAmountTf.setEnabled(false);

        placeTf.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.placeTf.text")); // NOI18N
        placeTf.setEnabled(false);

        javax.swing.GroupLayout resultPanelLayout = new javax.swing.GroupLayout(resultPanel);
        resultPanel.setLayout(resultPanelLayout);
        resultPanelLayout.setHorizontalGroup(
            resultPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(resultPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(resultPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(minAmountLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(amountLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(priceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(codeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(nameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(codeTf)
                    .addComponent(nameTf)
                    .addComponent(issuerLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(issuerTf)
                    .addComponent(priceTf, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(purPriceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
                    .addComponent(purPriceTf)
                    .addComponent(amountTf, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(minAmountTf)
                    .addComponent(placeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(placeTf))
                .addContainerGap())
        );
        resultPanelLayout.setVerticalGroup(
            resultPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(resultPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(codeLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(codeTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nameLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nameTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(issuerLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(issuerTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(priceLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(priceTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(purPriceLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(purPriceTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(amountLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(amountTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(minAmountLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(minAmountTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(placeLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(placeTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(47, 47, 47))
        );

        resultScrollPanel.setViewportView(resultPanel);

        addAnalogToOrderButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/add.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(addAnalogToOrderButton, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.addAnalogToOrderButton.text")); // NOI18N
        addAnalogToOrderButton.setToolTipText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.addAnalogToOrderButton.toolTipText")); // NOI18N
        addAnalogToOrderButton.setEnabled(false);
        addAnalogToOrderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addAnalogToOrderButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout searchPanelLayout = new javax.swing.GroupLayout(searchPanel);
        searchPanel.setLayout(searchPanelLayout);
        searchPanelLayout.setHorizontalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(resultScrollPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(findPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(сurrentOrderPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(analogsPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, searchPanelLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(addAnalogToOrderButton, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        searchPanelLayout.setVerticalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, searchPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(findPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(searchPanelLayout.createSequentialGroup()
                        .addComponent(сurrentOrderPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(addAnalogToOrderButton)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(analogsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(resultScrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 438, Short.MAX_VALUE))
                .addContainerGap())
        );

        shopPanel.addTab(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.searchPanel.TabConstraints.tabTitle"), searchPanel); // NOI18N

        searchControls.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        addPositionButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/add.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(addPositionButton, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.addPositionButton.text")); // NOI18N
        addPositionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addPositionButtonActionPerformed(evt);
            }
        });

        editPositionButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/edit.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(editPositionButton, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.editPositionButton.text")); // NOI18N
        editPositionButton.setEnabled(false);
        editPositionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editPositionButtonActionPerformed(evt);
            }
        });

        deletePositionButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/delete.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(deletePositionButton, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.deletePositionButton.text")); // NOI18N
        deletePositionButton.setEnabled(false);
        deletePositionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deletePositionButtonActionPerformed(evt);
            }
        });

        refreshButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/refresh.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(refreshButton, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.refreshButton.text")); // NOI18N
        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        positionsToBuy.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/ok.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(positionsToBuy, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.positionsToBuy.text")); // NOI18N
        positionsToBuy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                positionsToBuyActionPerformed(evt);
            }
        });

        localSearchField.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.localSearchField.text")); // NOI18N
        localSearchField.setToolTipText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.localSearchField.toolTipText")); // NOI18N
        localSearchField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                localSearchFieldActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(searchLabel, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.searchLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(printPriceLabelsLink, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.printPriceLabelsLink.text")); // NOI18N
        printPriceLabelsLink.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printPriceLabelsLinkActionPerformed(evt);
            }
        });

        clearPrintQueueButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/cancel.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(clearPrintQueueButton, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.clearPrintQueueButton.text")); // NOI18N
        clearPrintQueueButton.setToolTipText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.clearPrintQueueButton.toolTipText")); // NOI18N
        clearPrintQueueButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearPrintQueueButtonActionPerformed(evt);
            }
        });

        addPositionToPrintPriceLabelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/add.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(addPositionToPrintPriceLabelButton, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.addPositionToPrintPriceLabelButton.text")); // NOI18N
        addPositionToPrintPriceLabelButton.setToolTipText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.addPositionToPrintPriceLabelButton.toolTipText")); // NOI18N
        addPositionToPrintPriceLabelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addPositionToPrintPriceLabelButtonActionPerformed(evt);
            }
        });

        exportToExcellButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/save.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(exportToExcellButton, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.exportToExcellButton.text")); // NOI18N
        exportToExcellButton.setToolTipText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.exportToExcellButton.toolTipText")); // NOI18N
        exportToExcellButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportToExcellButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout searchControlsLayout = new javax.swing.GroupLayout(searchControls);
        searchControls.setLayout(searchControlsLayout);
        searchControlsLayout.setHorizontalGroup(
            searchControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchControlsLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addPositionButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(editPositionButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(deletePositionButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(printPriceLabelsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(addPositionToPrintPriceLabelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(clearPrintQueueButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(positionsToBuy)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(refreshButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addComponent(exportToExcellButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(searchLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(localSearchField, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        searchControlsLayout.setVerticalGroup(
            searchControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchControlsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(searchControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(clearPrintQueueButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(searchControlsLayout.createSequentialGroup()
                        .addGroup(searchControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(searchControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(localSearchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(searchLabel)
                                .addComponent(exportToExcellButton))
                            .addComponent(refreshButton)
                            .addGroup(searchControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(addPositionButton)
                                .addComponent(editPositionButton)
                                .addComponent(deletePositionButton)
                                .addComponent(positionsToBuy)
                                .addComponent(printPriceLabelsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(addPositionToPrintPriceLabelButton)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        shopTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                shopTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(shopTable);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.jLabel2.text")); // NOI18N

        summaBuyTextField.setEditable(false);
        summaBuyTextField.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.summaBuyTextField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.jLabel3.text")); // NOI18N

        summaSellTextField.setEditable(false);
        summaSellTextField.setText(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.summaSellTextField.text")); // NOI18N

        javax.swing.GroupLayout stockPanelLayout = new javax.swing.GroupLayout(stockPanel);
        stockPanel.setLayout(stockPanelLayout);
        stockPanelLayout.setHorizontalGroup(
            stockPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(stockPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(stockPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addComponent(searchControls, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(stockPanelLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(summaBuyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(summaSellTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        stockPanelLayout.setVerticalGroup(
            stockPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(stockPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(searchControls, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(stockPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(summaBuyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(summaSellTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE)
                .addGap(13, 13, 13))
        );

        shopPanel.addTab(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.stockPanel.TabConstraints.tabTitle"), stockPanel); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(shopPanel)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(shopPanel)
                .addContainerGap())
        );

        shopPanel.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(ShopTopComponent.class, "ShopTopComponent.shopPanel.AccessibleContext.accessibleName")); // NOI18N
    }// </editor-fold>//GEN-END:initComponents

    private void searchFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchFieldActionPerformed
        String code = searchField.getText();
        if (null != code && !code.isEmpty()) {
            String formattedCode = StringUtilities.formatPositionCode(StringUtilities.formatStringFromSpecialCharacters(code)).toUpperCase();
            searchField.setText(formattedCode);
            List<Position> pos = ShopDataProvider.getInstance().getPositionByCode(formattedCode);
            if (null == pos || pos.isEmpty()) {
                List<Position> positions = new ArrayList<>();
                positionTableModel = new PositionTableModel(positions);
                analogsTable.setModel(positionTableModel);
                UIUtils.showInfoMessage("Позиция не найдена");
            } else {
                currentlyFoundPosition = pos.get(0);
                List<Position> positions = ShopDataProvider.getInstance().getCrossPositionsByPositionId(currentlyFoundPosition.getId());
                positions.add(currentlyFoundPosition);
                positionTableModel = new PositionTableModel(positions);
                analogsTable.setModel(positionTableModel);
            }
            initializePositionInfo(currentlyFoundPosition);
        }
    }//GEN-LAST:event_searchFieldActionPerformed

    private void addAnalogToOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAnalogToOrderButtonActionPerformed
        Position selection = getPositionSelection();
        if (null != selection) {
            if (selection.getAmount() == 0) {
                UIUtils.showInfoMessage("Данная позиция временно отсутствует на складе");
                return;
            }
            clearOrderButton.setEnabled(true);
            orderPositions.add(selection);
            checkUpdatesForOrder();
        }
    }//GEN-LAST:event_addAnalogToOrderButtonActionPerformed

    private void clearOrderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearOrderButtonActionPerformed
        orderPositions.clear();
        clearOrderButton.setEnabled(false);
        checkUpdatesForOrder();
    }//GEN-LAST:event_clearOrderButtonActionPerformed

    private void currentOrderLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_currentOrderLinkActionPerformed
        // Implement logic to buy
        ConfirmPositionDialog dialog = new ConfirmPositionDialog(WindowManager.getDefault().getMainWindow(), true);
        dialog.setPositions(orderPositions);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
        clearOrderButtonActionPerformed(evt);
        searchFieldActionPerformed(evt);
    }//GEN-LAST:event_currentOrderLinkActionPerformed

    private void addPositionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPositionButtonActionPerformed
        PositionDialog dialog = new PositionDialog(WindowManager.getDefault().getMainWindow(), true);
        dialog.setPositionTableModel(shopTableModel);
        dialog.setLocationRelativeTo(null);
        dialog.setTitle("Добавить новую позицию в магазин");
        dialog.setVisible(true);
        calculateQuontity();
    }//GEN-LAST:event_addPositionButtonActionPerformed

    private void editPositionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editPositionButtonActionPerformed
        Position selection = getShopSelection();
        if (null != selection) {
            PositionDialog dialog = new PositionDialog(WindowManager.getDefault().getMainWindow(), true);
            dialog.setPositionTableModel(shopTableModel);
            dialog.setPosition(selection);
            dialog.setLocationRelativeTo(null);
            dialog.setTitle("Редактировать позицию");
            dialog.setVisible(true);
            calculateQuontity();
        }
    }//GEN-LAST:event_editPositionButtonActionPerformed

    private void deletePositionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deletePositionButtonActionPerformed
        Position selection = getShopSelection();
        if (null != selection) {
            shopTableModel.dataRemoved(selection);
            ShopDataProvider.getInstance().deletePosition(selection.getId());
            calculateQuontity();
        }
    }//GEN-LAST:event_deletePositionButtonActionPerformed

    private void shopTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_shopTableMouseClicked
        if (evt.getClickCount() == 2) {
            editPositionButtonActionPerformed(null);
        }
    }//GEN-LAST:event_shopTableMouseClicked

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        shopTableModel = new PositionTableModel();
        shopTable.setModel(shopTableModel);
        calculateQuontity();
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void positionsToBuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_positionsToBuyActionPerformed
        PositionsToBuyDialog dialog = new PositionsToBuyDialog(WindowManager.getDefault().getMainWindow(), true);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
    }//GEN-LAST:event_positionsToBuyActionPerformed

    private void localSearchFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_localSearchFieldActionPerformed
        String code = localSearchField.getText();
        if (null != code && !code.isEmpty()) {
            String formattedCode = StringUtilities.formatPositionCode(StringUtilities.formatStringFromSpecialCharacters(code)).toUpperCase();
            localSearchField.setText(formattedCode);
            shopTable.setRowFilter(RowFilter.andFilter(constructFilter(formattedCode)));
        } else {
            shopTable.setRowFilter(null);
        }
    }//GEN-LAST:event_localSearchFieldActionPerformed

    private void addPositionToPrintPriceLabelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPositionToPrintPriceLabelButtonActionPerformed
        if (positionsToPrint.size() == 9) {
            UIUtils.showInfoMessage("В корзине печати максимальное количество ценников.\nРаспечатайте их и очистите корзину.");
            return;
        }
        Position toPrint = getShopSelection();
        if (null != toPrint) {
            positionsToPrint.add(toPrint);
            printPriceLabelsLink.setText("Ценников на печать: " + positionsToPrint.size());
        }
    }//GEN-LAST:event_addPositionToPrintPriceLabelButtonActionPerformed

    private void clearPrintQueueButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearPrintQueueButtonActionPerformed
        positionsToPrint.clear();
        printPriceLabelsLink.setText("Ценников на печать: " + positionsToPrint.size());
    }//GEN-LAST:event_clearPrintQueueButtonActionPerformed

    private void printPriceLabelsLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printPriceLabelsLinkActionPerformed
        if (positionsToPrint.isEmpty() || positionsToPrint.size() > 9) {
            return;
        }
        try {
            HashMap parameters = new HashMap();
            BufferedImage logo = ImageIO.read(getClass().getClassLoader().getResource("logo_avtoz.jpg"));
            parameters.put("logo", logo);
            int i = 1;
            for (Position p : positionsToPrint) {
                parameters.put("name" + i, p.getName());
                parameters.put("code" + i, p.getCode());
                String price = p.getPrice().toString();
                if (price.endsWith(".0")) {
                    price += "0";
                }
                parameters.put("price" + i, price);
                parameters.put("producer" + i, p.getIssuer());
                ++i;
            }

            JasperPrint jp = ReportGenerator.getInstance().generateReport(parameters, ReportName.PRICE_LABEL);
            ReportGenerator.getInstance().showReport(jp);

        } catch (Exception ex) {
            ex.printStackTrace();
            UIUtils.showErrorMessage("Произошли ошибки при печати ценников");
        }
    }//GEN-LAST:event_printPriceLabelsLinkActionPerformed

    private void exportToExcellButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportToExcellButtonActionPerformed
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Сохранить файл как...");
        fileChooser.setSelectedFile(new java.io.File("Магазин.xls"));
        int result = fileChooser.showSaveDialog(WindowManager.getDefault().getMainWindow());
        if (result != JFileChooser.APPROVE_OPTION) {
            return;
        }

        try {
            Files.write(fileChooser.getSelectedFile().toPath(), ExportUtils.exportToExcel(shopTable));
        } catch (Exception ex) {
            ex.printStackTrace();
            UIUtils.showErrorMessage("Произошли ошибки при сохранении файла");
        }
    }//GEN-LAST:event_exportToExcellButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addAnalogToOrderButton;
    private javax.swing.JButton addPositionButton;
    private javax.swing.JButton addPositionToPrintPriceLabelButton;
    private javax.swing.JLabel amountLabel;
    private javax.swing.JTextField amountTf;
    private javax.swing.JPanel analogsPanel;
    private org.jdesktop.swingx.JXTable analogsTable;
    private javax.swing.JButton clearOrderButton;
    private javax.swing.JButton clearPrintQueueButton;
    private javax.swing.JLabel codeLabel;
    private javax.swing.JTextField codeTf;
    private org.jdesktop.swingx.JXHyperlink currentOrderLink;
    private javax.swing.JButton deletePositionButton;
    private javax.swing.JButton editPositionButton;
    private javax.swing.JButton exportToExcellButton;
    private javax.swing.JPanel findPanel;
    private javax.swing.JLabel issuerLabel;
    private javax.swing.JTextField issuerTf;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private org.jdesktop.swingx.JXSearchField localSearchField;
    private javax.swing.JLabel minAmountLabel;
    private javax.swing.JTextField minAmountTf;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameTf;
    private javax.swing.JLabel placeLabel;
    private javax.swing.JTextField placeTf;
    private javax.swing.JButton positionsToBuy;
    private javax.swing.JLabel priceLabel;
    private javax.swing.JTextField priceTf;
    private org.jdesktop.swingx.JXHyperlink printPriceLabelsLink;
    private javax.swing.JLabel purPriceLabel;
    private javax.swing.JTextField purPriceTf;
    private javax.swing.JButton refreshButton;
    private javax.swing.JPanel resultPanel;
    private javax.swing.JScrollPane resultScrollPanel;
    private javax.swing.JPanel searchControls;
    private org.jdesktop.swingx.JXSearchField searchField;
    private javax.swing.JLabel searchLabel;
    private javax.swing.JPanel searchPanel;
    private javax.swing.JTabbedPane shopPanel;
    private org.jdesktop.swingx.JXTable shopTable;
    private javax.swing.JPanel stockPanel;
    private javax.swing.JTextField summaBuyTextField;
    private javax.swing.JTextField summaSellTextField;
    private javax.swing.JPanel сurrentOrderPanel;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    private void initializePositionInfo(Position pos) {
        if (null != pos) {
            codeTf.setText(pos.getCode());
            nameTf.setText(pos.getName());
            issuerTf.setText(pos.getIssuer() == null ? "" : pos.getIssuer());
            priceTf.setText(pos.getPrice().toString());
            purPriceTf.setText(pos.getPurPrice().toString());
            amountTf.setText(pos.getAmount().toString());
            minAmountTf.setText(pos.getMinAmount().toString());
            placeTf.setText(pos.getPlace() == null ? "" : pos.getPlace());
        } else {
            codeTf.setText("");
            nameTf.setText("");
            issuerTf.setText("");
            priceTf.setText("");
            purPriceTf.setText("");
            amountTf.setText("");
            minAmountTf.setText("");
            placeTf.setText("");
        }
    }

    protected Position getPositionSelection() {
        if (analogsTable.getSelectedRow() > -1) {
            Position pos = (Position) analogsTable
                    .getValueAt(analogsTable.getSelectedRow(), -1);
            return pos;
        }
        return null;
    }

    protected Position getShopSelection() {
        if (shopTable.getSelectedRow() > -1) {
            Position pos = (Position) shopTable
                    .getValueAt(shopTable.getSelectedRow(), -1);
            return pos;
        }
        return null;
    }

    private void checkUpdatesForOrder() {
        if (null != orderPositions) {
            Double sum = 0.0;
            for (Position pos : orderPositions) {
                sum += pos.getPrice();
            }
            currentOrderLink.setText("Текущий заказ: " + sum.toString() + " руб.");
        }
    }

    private List<RowFilter<Object, Object>> constructFilter(String text) {
        List<RowFilter<Object, Object>> filters = new ArrayList<>();
        filters.add(RowFilter.regexFilter(text));
        return filters;
    }

    private void calculateQuontity() {
        Double price = 0.0;
        Double purPrice = 0.0;
        for (int i = 0; i < shopTable.getRowCount(); ++i) {
            Position pos = (Position) shopTable
                    .getValueAt(i, -1);
            if (null != pos) {
                price += (pos.getPrice() * pos.getAmount());
                purPrice += (pos.getPurPrice() * pos.getAmount());
            }
        }
        summaBuyTextField.setText("" + MathUtils.round(purPrice, 2));
        summaSellTextField.setText("" + MathUtils.round(price, 2));
    }
}
